"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { ChevronDown } from "lucide-react"
import { getPlaylistCategories } from "@/lib/api-client"

interface PlaylistCategory {
  id: number | string
  name: string
}

interface CategoryGroup {
  [key: string]: PlaylistCategory[]
}

interface PlaylistCategoriesProps {
  selectedCategory: number | string | null
  onCategoryChange: (category: number | string | null) => void
  recentlyUsed?: PlaylistCategory[]
}

export function PlaylistCategories({ selectedCategory, onCategoryChange, recentlyUsed = [] }: PlaylistCategoriesProps) {
  const [categories, setCategories] = useState<CategoryGroup>({})
  const [moreCategories, setMoreCategories] = useState<CategoryGroup>({})
  const [categoryNames, setCategoryNames] = useState<Record<string, string>>({})
  const [showMoreCategories, setShowMoreCategories] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  // 获取分类数据
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        setIsLoading(true)
        const response = await getPlaylistCategories()

        if (response.success) {
          setCategories(response.data.categories || {})
          setMoreCategories(response.data.moreCategories || {})
          setCategoryNames(response.data.categoryNames || {})
        }
      } catch (error) {
        console.error("获取歌单分类失败:", error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchCategories()
  }, [])

  // 处理分类选择
  const handleCategorySelect = (category: PlaylistCategory) => {
    onCategoryChange(selectedCategory === category.id ? null : category.id)

    // 关闭更多分类面板
    setShowMoreCategories(null)
  }

  // 处理"更多"按钮点击
  const handleMoreClick = (groupId: string) => {
    setShowMoreCategories(showMoreCategories === groupId ? null : groupId)
  }

  if (isLoading) {
    return (
        <div className="space-y-6 animate-pulse">
          {[...Array(5)].map((_, index) => (
              <div key={index} className="flex items-start gap-4">
                <div className="w-20 h-4 bg-muted rounded"></div>
                <div className="flex-1">
                  <div className="flex flex-wrap gap-2">
                    {[...Array(8)].map((_, btnIndex) => (
                        <div key={btnIndex} className="h-8 w-20 bg-muted rounded-full"></div>
                    ))}
                  </div>
                </div>
              </div>
          ))}
        </div>
    )
  }

  return (
      <div className="space-y-6">
        {/* 最近常用 */}
        {recentlyUsed.length > 0 && (
            <div className="flex items-start gap-4">
              <span className="text-sm font-medium text-muted-foreground w-20">{categoryNames["0"] || "最近常用"}</span>
              <div className="flex-1">
                <div className="flex flex-wrap gap-2">
                  {recentlyUsed.map((category) => (
                      <Button
                          key={`${category.id}-${category.name}`}  // 结合 id 和 name
                          variant="ghost"
                          size="sm"
                          data-category-id={category.id}
                          className={cn(
                              "h-8 rounded-full",
                              selectedCategory === category.id && "bg-primary text-primary-foreground hover:bg-primary/90",
                          )}
                          onClick={() => handleCategorySelect(category)}
                      >
                        {category.name}
                      </Button>
                  ))}
                </div>
              </div>
            </div>
        )}

        {/* 其他分类 */}
        {Object.entries(categories).map(([groupId, items]) => {
          const groupName = categoryNames[groupId] || `分类${groupId}`

          return (
              <div key={groupId} className="flex items-start gap-4">
                <span className="text-sm font-medium text-muted-foreground w-20">{groupName}</span>
                <div className="flex-1">
                  <div className="flex flex-wrap gap-2">
                    {items.map((category) => (
                        <Button
                            key={category.id}
                            variant="ghost"
                            size="sm"
                            data-category-id={category.id}
                            className={cn(
                                "h-8 rounded-full",
                                selectedCategory === category.id && "bg-primary text-primary-foreground hover:bg-primary/90",
                            )}
                            onClick={() => handleCategorySelect(category)}
                        >
                          {category.name}
                        </Button>
                    ))}
                    {moreCategories[groupId] && (
                        <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 rounded-full text-muted-foreground"
                            onClick={() => handleMoreClick(groupId)}
                        >
                          更多
                          <ChevronDown
                              className={cn(
                                  "ml-1 h-4 w-4 transition-transform",
                                  showMoreCategories === groupId && "transform rotate-180",
                              )}
                          />
                        </Button>
                    )}
                  </div>

                  {/* 更多分类展开面板 */}
                  {showMoreCategories === groupId && moreCategories[groupId] && (
                      <div className="mt-4 space-y-4 bg-muted/50 rounded-lg p-4">
                        <div className="grid grid-cols-[repeat(auto-fill,_minmax(80px,_1fr))] gap-2">
                          {moreCategories[groupId].map((category) => (
                              <Button
                                  key={category.id}
                                  variant="ghost"
                                  size="sm"
                                  data-category-id={category.id}
                                  className={cn(
                                      "h-8 rounded-full w-full",
                                      selectedCategory === category.id && "bg-primary text-primary-foreground hover:bg-primary/90",
                                  )}
                                  onClick={() => handleCategorySelect(category)}
                              >
                                {category.name}
                              </Button>
                          ))}
                        </div>
                      </div>
                  )}
                </div>
              </div>
          )
        })}
      </div>
  )
}

